package stackdemo;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA
 * Description:  实现简单的栈
 * User: SEKI TOMOKI
 * Date: 2023-10-10
 * Time: 14:41
 */
public class MyStack implements IList {
    private int[] stack;
    private int usedSize;
    private static final int DEFAULT_CAPACITY = 10;
    public MyStack() {
        stack = new int[DEFAULT_CAPACITY];
    }

    @Override
    public int push(int elem) {
        if(full()) {
            stack = Arrays.copyOf(stack,2*usedSize);
        }
        stack[usedSize] = elem;
        usedSize++;
        return elem;
    }

    @Override
    public int pop() {
        if(empty()) {
            throw new EmptyException("栈是空的。");
        }
        int old = stack[usedSize - 1];
        usedSize--;
        //如果是引用数据类型，要出栈的位置要置为null
        //stack[usedSize - 1] = null;
        return old;
    }

    @Override
    public int peek() {
        if(empty()) {
            throw new EmptyException("栈是空的。");
        }
        return stack[usedSize - 1];
    }

    @Override
    public int size() {
        return usedSize;
    }

    @Override
    public boolean empty() {
        if(usedSize == 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean full() {
        if(usedSize == stack.length) {
            return true;
        }
        return false;
    }

    @Override
    public String toString() {
        return "MyStack{" +
                "stack=" + Arrays.toString(stack) +
                '}';
    }
}
